package com.bancomer.batch.converters.impl;

import java.io.File;
import java.util.Properties;

import com.bancomer.batch.Constants;
import com.bancomer.batch.MapConstants;
import com.bancomer.batch.converters.AuditAlert;
import com.bancomer.batch.converters.FileToObjectsConverter;
import com.bancomer.batch.converters.FlatWormWriter;
import com.bancomer.batch.converters.GeneralConverter;
import com.bancomer.batch.pojo.Alert;
import com.bancomer.batch.pojo.ConverterResult;
import com.bancomer.batch.pojo.FileHelper;
import com.bancomer.batch.pojo.SummaryDetail;
import com.bancomer.batch.util.FilesWriter;
import com.bancomer.batch.util.LinuxCommand;

public class FlatWormConverter implements GeneralConverter {
	
	@Override
	public ConverterResult executeConversion(Object... obj) {
		ConverterResult result = new ConverterResult();
		Alert alert = null;
		FileHelper summaryFile = null;
		FileHelper detailFile = null;
		Properties alertConstants = null;
		try{
		for(Object element:obj){
			if(element instanceof Properties){
				alertConstants=(Properties)element;	
			}
			if(element instanceof Alert){
				alert=(Alert)element;	
			}
			if(element instanceof FileHelper){
				FileHelper file = (FileHelper)element;
				if(file.getProperties().getProperty("outputType").equals(alertConstants.getProperty("OUTPUT_TYPE_SUMMARY"))){
					summaryFile = file;
				}
				if(file.getProperties().getProperty("outputType").equals(alertConstants.getProperty("OUTPUT_TYPE_DETAIL"))){
					detailFile=file;
				}
			}
		}
		
		AuditAlert auditSumary = FileToObjectsConverter.getObjectsFromSummary(alert);
		AuditAlert auditDetail =  FileToObjectsConverter.getObjectsFromDetail(alert);
		File summary = new File(summaryFile.getLocalPath()+summaryFile.getName());
		File detail = new File(detailFile.getLocalPath()+detailFile.getName());
		if(summary.exists()){
			LinuxCommand.execute("rm -f "+summaryFile.getLocalPath()+summaryFile.getName(), true);
		}
		if(detail.exists()){
			LinuxCommand.execute("rm -f "+detailFile.getLocalPath()+detailFile.getName(), true);
		}
		FlatWormWriter.create(alertConstants,summaryFile.getProperties().getProperty(alertConstants.getProperty("XML_OUTPUT_CONFIG")), summaryFile.getLocalPath()+summaryFile.getName(), auditSumary);
		FlatWormWriter.create(alertConstants,detailFile.getProperties().getProperty(alertConstants.getProperty("XML_OUTPUT_CONFIG")), detailFile.getLocalPath()+detailFile.getName(), auditDetail);
		FilesWriter.writeFile("OK-"+Constants.alertDate,summaryFile.getLocalPath()+"SUCCESS", false);
		}
		catch(Exception e){
			result.setMessage(e.getMessage());
			result.setSucces(false);
		}
		// TODO Auto-generated method stub
		return result;
	}
	
}
